/**
 * @Desc:
 * @User: zouqihui
 * @Date: 2022/12/12 16:22
 */
package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UploadController struct {
	beego.Controller
}

// Index
// Url :http://127.0.0.1:8080/upload/index
// Desc: 上传文件页面
// User: zouqihui
// Date: 2022-12-12 18:52:45
// @receiver c
func (c *UploadController) Index() {
	c.TplName = "upload.tpl"
}

// Upload
// Desc: 上传文件
// User: zouqihui
// Date: 2022-12-12 18:52:35
// @receiver c
func (c *UploadController) Upload() {
	uploadName := "uploadname"
	f, m, err := c.GetFile(uploadName)
	//fmt.Println(f, m)
	if err != nil {
		//log.Fatal("uplaod: getfile err ", err)
		//fmt.Println("upload file: getfile err ", err)
		c.Ctx.WriteString("上传文件必须：" + err.Error())
		//c.Data["json"] = "上传文件必须：" + err.Error()
		//c.ServeJSON()
		//c.Redirect("/upload/index", 302)
	} else {
		defer f.Close()
		timeStr := time.Now().Format("20060102150405")
		filePath := "static/uploads/" + timeStr + "_" + m.Filename
		err = c.SaveToFile(uploadName, filePath)
		if err != nil {
			fmt.Println("upload failed： ", err)
			c.Data["json"] = err
		} else {
			hostname := c.Ctx.Request.Host
			c.Data["json"] = hostname + "/" + filePath
		}

		c.ServeJSON()
	}

}
